package com.wes.dsptest.audioalarm;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wes.dsptest.R;
import com.wes.dsptest.data.TinySharedPreferences;
import com.xw.repo.BubbleSeekBar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class AudioFragment extends Fragment implements View.OnClickListener, IAudioControl, DatePickerDialog.OnDateSetListener {

    private static final String MUSIC_NAME = "mName";
    private static AudioFunction audioFunction;
    private View rootView;
    private TextView tvText;
    private Button btnFile;
    private TextView tvMusicName;
    private ImageView ivPlay;
    private Button btnAlarmTime;
    private TextView tvAlarmTime;
    private TextView tvCurTime;
    private Context context;

    private Runnable updatetimeRunnable;
    private Switch swAlarm;
    private TextView tvLeftTime;
    private TextView tvPosTime;
    private BubbleSeekBar sbProgress;
    private final static String TAG = "AudioFragment";
    private Button btnDate;

    private AudioReceiver audioReceiver;

    public AudioFragment() {
    }

    public static AudioFragment newInstance(String param1) {
        AudioFragment fragment = new AudioFragment();
        Bundle args = new Bundle();
        args.putString(MUSIC_NAME, param1);
        fragment.setArguments(args);
        return fragment;
    }

    private void initAudio() {
        audioFunction = new AudioFunction(context, this);
        audioReceiver = new AudioReceiver();
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction("com.wes.dsptest");
        getActivity().registerReceiver(audioReceiver, iFilter);
    }

    private String getTime(int milliSeconds) {
        int seconds = milliSeconds / 1000;
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }

    @Override
    public void getMaxMusicPosition(int max) {
        sbProgress.getConfigBuilder().max(max).build();
    }

    @Override
    public boolean getMusicPlayStatus() {
        return false;
    }

    @Override
    public void curPostion(int pos) {
        sbProgress.setProgress(pos);
        tvPosTime.setText(getTime(pos));

    }

    @Override
    public void onComplettion() {
        audioFunction.getAudioPlayerUtil().stopPlayer();
        //UI
        ivPlay.setSelected(false);
        setSeekBarProgressEnable(false);
        sbProgress.setProgress(0);
        tvPosTime.setText(getTime(0));
    }

    public class AudioReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("cmd");
//            if(msg == "alarm")
            {
//                audioFunction.getAudioAlarm().playMusic();
                long diff =  alarmTimeUtil.getTimeDifference(audioFunction.getAudioAlarm().getStringAlarmTime(), getCurTime());

                Toast.makeText(context, "播放铃声:" + msg + " diff:" + diff, Toast.LENGTH_SHORT).show();
                playMusic(true);  //强制播放
            }
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
        initAudio();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null && audioFunction != null) {
            audioFunction.setMusicName(getArguments().getString(MUSIC_NAME));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_audio, container, false);
        // Inflate the layout for this fragment
        initView();
        //update time
        updatetime();
        return rootView;
    }

    private String getCurTime() {

        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        String timeStr = format.format(now);
        return timeStr;
    }

    private void updatetime() {

        Handler handler = new Handler(Looper.getMainLooper());

        updatetimeRunnable = new Runnable() {
            @Override
            public void run() {
                String curTime = getCurTime();
                String left = alarmTimeUtil.getStringTimeDifference(audioFunction.getStringAlarmTime(), curTime);

                // 更新 UI
                tvCurTime.setText(curTime);
                tvLeftTime.setText(left);


                // 循环执行
                handler.postDelayed(updatetimeRunnable, 1000);
            }
        };
        handler.post(updatetimeRunnable);
    }

    private void setSeekBarProgressEnable(boolean enable) {
        sbProgress.setClickable(enable);
        sbProgress.setEnabled(enable);
        sbProgress.setSelected(enable);
        sbProgress.setFocusable(enable);

    }

    private void initView() {
        tvText = rootView.findViewById(R.id.tvTitle);
        tvMusicName = rootView.findViewById(R.id.tvMusicName);
        btnFile = rootView.findViewById(R.id.btn_file);
        ivPlay = rootView.findViewById(R.id.ivPlay);
        btnAlarmTime = rootView.findViewById(R.id.btn_setAlarmTime);
        tvAlarmTime = rootView.findViewById(R.id.tvAlarmTime);
        tvCurTime = rootView.findViewById(R.id.tvCurTime);
        tvLeftTime = rootView.findViewById(R.id.tvLeftTime);
        swAlarm = rootView.findViewById(R.id.sw_alarm);
        tvPosTime = rootView.findViewById(R.id.tv_pos_time);

        btnDate = rootView.findViewById(R.id.btn_date);

        sbProgress = rootView.findViewById(R.id.sb_music);
        sbProgress.setTrackColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
        sbProgress.setSecondTrackColor(ContextCompat.getColor(getContext(), R.color.color_blue_deep));
        sbProgress.setBubbleColor(ContextCompat.getColor(getContext(), R.color.color_blue_deep));
        sbProgress.setThumbColor(ContextCompat.getColor(getContext(), R.color.color_blue_deep));
        sbProgress.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                Log.i(TAG, "onchanged +" + progress);
                tvPosTime.setText(getTime(progress));
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

                audioFunction.getAudioPlayerUtil().setMusicPostion(bubbleSeekBar.getProgress());
                tvPosTime.setText(getTime(bubbleSeekBar.getProgress()));
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                Log.i(TAG, "getProgressOnFinally: +" + progress);
            }
        });
        setSeekBarProgressEnable(false);

        tvMusicName.setText(audioFunction.getMusicName());
        btnFile.setOnClickListener(this);
        btnAlarmTime.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        btnDate.setOnClickListener(this);

        swAlarm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    audioFunction.openAudioAlarm(true);
                    swAlarm.setText(R.string.alarmOpen);
                } else {
                    audioFunction.openAudioAlarm(false);
                    swAlarm.setText(R.string.alarmClose);
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_file:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(Intent.createChooser(intent, "需要选择文件"), 1);
                break;
            case R.id.btn_setAlarmTime:
                setAlarmTime();
                break;
            case R.id.ivPlay:
                playMusic(false);  //不强制播放
                break;
            case R.id.btn_date:
                showDatePickerDialog();
                break;
        }
    }

    private void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
                this,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );

        // 启用星期显示
        datePickerDialog.show(getFragmentManager(), "DatePickerDialog");
        datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_2);
        datePickerDialog.setThemeDark(true);
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, monthOfYear, dayOfMonth);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd (EEEE)", Locale.getDefault());
        String selectedDate = dateFormat.format(calendar.getTime());
        Log.i(TAG, "date:" + selectedDate);
    }


    private void playMusic(boolean force) {
        if (!audioFunction.getAudioPlayerUtil().isHavePlayer()) {
            audioFunction.getAudioPlayerUtil().createPlayer(audioFunction.getMusicName());
            setSeekBarProgressEnable(true);
            ivPlay.setSelected(true);
        } else if (force) {
            audioFunction.getAudioPlayerUtil().stopPlayer();
            audioFunction.getAudioPlayerUtil().createPlayer(audioFunction.getMusicName());
            setSeekBarProgressEnable(true);
            ivPlay.setSelected(true);
        } else {
            if (audioFunction.getAudioPlayerUtil().isPlaying()) {
                audioFunction.getAudioPlayerUtil().pausePlayer();
                setSeekBarProgressEnable(false);
                ivPlay.setSelected(false);
            } else {
                audioFunction.getAudioPlayerUtil().startPlayer();
                setSeekBarProgressEnable(true);
                ivPlay.setSelected(true);
            }
        }
    }

    private void setAlarmTime() {
        TimePickerDialog tpd = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
                audioFunction.setAlarmTime(hourOfDay, minute);
                tvAlarmTime.setText(audioFunction.getStringAlarmTime());
                Toast.makeText(getActivity(), audioFunction.getStringAlarmTime(), Toast.LENGTH_SHORT).show();

            }
        }, 13, 30, true);
        tpd.show();

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            Uri uri = data.getData();
            String pathString = UriUtil.getPath(getActivity(), uri);

            tvMusicName.setText(pathString);
            if (audioFunction.getMusicName() != pathString) {
                audioFunction.setMusicName(pathString);
                setFileMusicName(pathString);
            }
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        context = null;
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(audioReceiver);
        super.onDestroy();
    }

    private void setFileMusicName(String name) {
        TinySharedPreferences tsp = TinySharedPreferences.instance(getActivity());
        tsp.setStringValue("MusicName", name);
    }
}